<template>
  <div class="wrap-container">
    <div class="search_box">
      <div class="search_tit">优惠券查询</div>
      <el-form :inline="true" label-position="left" label-width="84px">
        <el-form-item label="优惠券名称">
          <el-input v-model="queryParams.couponName" placeholder="请输入" clearable></el-input>
        </el-form-item>
        <el-form-item label="优惠券类型">
          <el-select filterable clearable v-model="queryParams.type" placeholder="请选择">
            <el-option
              v-for="dict in dict?.type?.platform_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="优惠券状态">
          <el-select filterable clearable v-model="queryParams.enable" placeholder="请选择">
            <el-option
              v-for="dict in enableOptions"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item class="search_btn">
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 操作栏 -->
    <div class="table_box">
      <div class="handle_btn">
        <el-button type="primary" v-hasPermi="['sys:coupon:btn_add']" @click="handleAdd"
          >新增优惠券</el-button
        >
        <el-button class="del_btn" v-hasPermi="['sys:coupon:btn_stop']" @click="handleDel(1)"
          >批量终止</el-button
        >
        <el-button class="del_btn" v-hasPermi="['sys:coupon:btn_remove']" @click="handleDel(1)"
          >批量删除</el-button
        >
      </div>

      <!-- 数据表格 -->
      <el-table :data="list" v-loading="loading" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="50"> </el-table-column>
        <el-table-column prop="couponName" label="优惠券名称" />
        <el-table-column prop="type" label="平台类型" width="100">
          <template #default="{ row }">
            {{ typeFormat(row.type) }}
          </template>
        </el-table-column>
        <el-table-column prop="enable" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.enable ? 'success' : 'danger'">
              {{ row.enable ? '启用' : '停用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="enableTime" label="启用/停用时间" width="180" />
        <el-table-column prop="stadiumName" label="场馆名称" width="auto" />
        <el-table-column prop="siteName" label="场地名称" width="auto" />
        <el-table-column prop="validity" label="有效时间" width="100" />
        <el-table-column prop="motionType" label="运动类型" width="120">
          <template #default="{ row }">
            <el-tag>
              {{ motionTypeFormat(row) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="auto" />
        <el-table-column prop="updateTime" label="更新时间" width="auto" />
        <el-table-column label="操作" width="150">
          <template #default="{ row }">
            <el-button
              v-if="row.isSpecify == 0"
              type="text"
              v-hasPermi="['sys:coupon:btn_send']"
              @click="grantCoupon(row)"
              >发放</el-button
            >
            <el-button type="text" v-hasPermi="['sys:coupon:btn_update']" @click="handleEdit(row)"
              >编辑</el-button
            >
            <el-button
              type="text"
              v-hasPermi="['sys:coupon:btn_open_update']"
              :style="{ color: row.enable ? '#F56C6C' : '#67C23A' }"
              @click="toggleStatus(row)"
            >
              {{ row.enable ? '停用' : '启用' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </div>

    <!-- 发放优惠券对话框 -->
    <el-dialog :title="title" v-model="openGrant" width="600px" @close="handleClose">
      <el-form ref="grantFormRef" :model="grantForm" :rules="grantRules" label-width="126px">
        <el-form-item label="用户手机号" prop="userId">
          <el-select
            v-model="grantForm.userId"
            placeholder="请选择用户"
            clearable
            multiple
            filterable
            allow-create
            default-first-option
          >
            <el-option
              v-for="item in userList"
              :key="item.id"
              :label="item.mobile"
              :value="item.mobile.toString()"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div>
          <el-button @click="grantClose">取消</el-button>
          <el-button type="primary" @click="submitGrant">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="title"
      v-model="open"
      width="600px"
      @close="handleClose"
      :close-on-click-modal="false"
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="126px">
        <el-form-item label="优惠券名称" prop="couponName">
          <el-input clearable v-model="form.couponName" placeholder="请输入优惠券名称" />
        </el-form-item>
        <el-form-item label="平台类型" prop="type">
          <el-select
            filterable
            clearable
            v-model="form.type"
            placeholder="请选择平台类型"
            @change="changePlatformType"
          >
            <el-option
              v-for="dict in dict?.type?.platform_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="是否需发放用户" prop="isSpecify">
          <el-radio-group v-model="form.isSpecify">
            <el-radio :label="'0'">是</el-radio>
            <el-radio :label="'1'">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="运动类型" prop="motionType" v-if="!typeDisabled">
          <el-select
            filterable
            clearable
            v-model="form.motionType"
            placeholder="请选择运动类型"
            size="small"
            @change="changeMotionType"
          >
            <el-option
              v-for="dict in dict?.type?.site_type"
              :key="dict.value"
              :value="Number(dict.value)"
              :label="dict.label"
            />
          </el-select>
        </el-form-item>
        <template v-if="!isDisabled">
          <el-form-item label="场馆" prop="stadiumName">
            <el-select
              v-model="form.stadiumName"
              filterable
              remote
              reserve-keyword
              clearable
              placeholder="请输入场馆名"
              :remote-method="searchStadium"
              :loading="stadiumLoading"
              @change="handleStadiumChange"
              :disabled="isDisabled"
            >
              <el-option
                v-for="item in stadiumOptions"
                :key="item.id"
                :label="item.stadiumName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="场地" prop="siteName">
            <el-select
              v-model="form.siteName"
              filterable
              clearable
              placeholder="请选择场地"
              @change="handleSiteChange"
              :disabled="isDisabled"
            >
              <el-option
                v-for="item in siteOptions"
                :key="item.id"
                :label="item.siteName"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </template>
        <el-form-item label="优惠券类型" prop="discountType">
          <el-select
            v-model="form.discountType"
            placeholder="请选择优惠券类型"
            @change="handleChange"
            filterable
            clearable
          >
            <el-option
              v-for="dict in dict?.type?.discount_type"
              :key="dict.value"
              :value="Number(dict.value)"
              :label="dict.label"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="优惠券金额" prop="discountAmount" v-if="!isQMShow">
          <el-input
            maxlength="8"
            v-model="form.discountAmount"
            placeholder="请输入金额"
            style="width: 100%"
            clearable
          ></el-input>
        </el-form-item>

        <el-form-item v-if="isQMShow">
          <template #label>
            <!--            <i style="margin-right: 4px; color: #ff4949">*</i>-->
            全免券使用时间
          </template>
          <div class="align_center">
            <el-form-item prop="startTime">
              <el-time-select
                placeholder="开始时间"
                v-model="form.startTime"
                :picker-options="{
                  start: '00:00',
                  step: '00:60',
                  end: '24:00',
                }"
                clearable
              >
              </el-time-select>
            </el-form-item>
            <el-form-item prop="endTime">
              <el-time-select
                placeholder="结束时间"
                v-model="form.endTime"
                :picker-options="{
                  start: '00:00',
                  step: '00:60',
                  end: '24:00',
                }"
                clearable
              >
              </el-time-select>
            </el-form-item>
          </div>
        </el-form-item>
        <el-form-item v-if="isMJShow" label="满减券总额度" prop="totalLimit">
          <el-input
            maxlength="8"
            v-model="form.totalLimit"
            placeholder="请输入金额"
            style="width: 100%"
            clearable
          ></el-input>
        </el-form-item>

        <el-form-item label="领取后有效期（单位：天）" prop="validity">
          <el-input type="number" v-model="form.validity" placeholder="请输入领取后有效期" />
        </el-form-item>
        <el-form-item label="优惠券备注" prop="remark">
          <el-input
            clearable
            type="textarea"
            placeholder="请输入内容"
            v-model="form.remark"
            maxlength="30"
            show-word-limit
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div>
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useDict } from '@/utils/dict'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { addCoupon, listCoupon, updateCoupon, updateStatus, grantCoupon } from '@/api/coupon/coupon'
import { getSitesByStadiumId, quickSearchStadium } from '@/api/site/site'
import { debounce } from 'lodash'
import { getPage } from '@/api/user/user'

// 字典数据
const { dict } = useDict({
  dicts: ['site_type', 'discount_type', 'platform_type', 'sys_normal_disable'],
})

// 定义响应式数据
const router = useRouter()
const list = ref<any[]>([])
const total = ref(0)
const loading = ref(false)
const open = ref(false)
const openGrant = ref(false)
const title = ref('')
const isQMShow = ref(false)
const isMJShow = ref(false)
const stadiumLoading = ref(false)
const stadiumOptions = ref<any[]>([])
const siteOptions = ref<any[]>([])
const isDisabled = ref(false)
const typeDisabled = ref(false)
const userList = ref<any[]>([])
const multipleSelection = ref<any[]>([])

const formRef = ref<FormInstance | null>(null)
const grantFormRef = ref<FormInstance | null>(null)

const grantForm = reactive({
  couponId: '',
  userId: [] as string[],
})

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  couponName: null as string | null,
  type: null as string | null,
  enable: null as number | null,
})

const form = reactive({
  id: null as number | null,
  couponName: null as string | null,
  type: null as string | null,
  enable: null as number | null,
  stadiumId: null as number | null,
  siteId: null as number | null,
  motionType: null as number | null,
  validity: null as number | null,
  stadiumName: null as number | null,
  siteName: null as number | null,
  startTime: null as string | null,
  endTime: null as string | null,
  discountType: null as number | null,
  totalLimit: 0.0,
  discountAmount: 0.0,
  isSpecify: null as string | null,
})

const enableOptions = [
  {
    value: 1,
    label: '启用',
  },
  {
    value: 0,
    label: '停用',
  },
]

const rules = reactive<FormRules>({
  couponName: [
    {
      required: true,
      message: '请输入优惠券名称',
      trigger: 'blur',
    },
  ],
  type: [
    {
      required: true,
      message: '请选择平台类型',
      trigger: 'change',
    },
  ],
  motionType: [
    {
      required: true,
      message: '请选择运动类型',
      trigger: 'change',
    },
  ],
  stadiumName: [
    {
      required: true,
      message: '请选择运动类型',
      trigger: 'change',
    },
  ],
  siteName: [
    {
      required: true,
      message: '请选择场地',
      trigger: 'change',
    },
  ],
  discountType: [
    {
      required: true,
      message: '请选择优惠券类型',
      trigger: 'change',
    },
  ],
  discountAmount: [
    {
      required: true,
      message: '请输入优惠券金额',
      trigger: 'blur',
    },
  ],
  validity: [
    {
      required: true,
      message: '请输入领取后有效期',
      trigger: 'blur',
    },
  ],
  remark: [
    {
      required: true,
      message: '请输入优惠券备注',
      trigger: 'blur',
    },
  ],
  totalLimit: [
    {
      required: true,
      message: '请输入满减券总额度',
      trigger: 'blur',
    },
  ],
  // startTime: [
  //   {
  //     required: true,
  //     message: "请选择开始时间",
  //     trigger: "blur",
  //   },
  // ],
  // endTime: [
  //   {
  //     required: true,
  //     message: "请选择结束时间",
  //     trigger: "blur",
  //   },
  // ],
  isSpecify: [
    {
      required: true,
      message: '请选择是否需发放用户',
      trigger: 'blur',
    },
  ],
})

const grantRules = reactive<FormRules>({
  userId: [{ required: true, message: '请选择用户', trigger: 'blur' }],
})

// 获取数据列表
const getList = async () => {
  loading.value = true
  try {
    const res: any = await listCoupon(queryParams)
    list.value = res.rows
    total.value = res.total
  } finally {
    loading.value = false
  }
}

// 新增
const handleAdd = () => {
  router.push({ path: '/coupon/add' })
}

// 编辑
const handleEdit = (row: any) => {
  router.push({
    path: '/coupon/add',
    query: { data: JSON.stringify(row) },
  })
  // if (row.discountType == "2") {
  //   isQMShow.value = true;
  // } else {
  //   isQMShow.value = false;
  // }
  // isDisabled.value = row.type == 2 || row.type == 3 ? true : false;
  // typeDisabled.value = row.type == 3 ? true : false;
  // form = { ...row };
  // title.value = "修改优惠券";
  // open.value = true;
  // if (form.stadiumId) {
  //   handlSearchSiteByStadiumId();
  // }
  // nextTick(() => {
  //   formRef.value?.clearValidate();
  // });
  // changePlatformType(form.type);
}

// 发放优惠券
const grantCoupon = (row: any) => {
  title.value = '发放优惠券'
  openGrant.value = true
  grantForm.couponId = row.id
}

// 状态切换
const toggleStatus = async (row: any) => {
  try {
    await ElMessageBox.confirm(`确认${row.enable ? '停用' : '启用'}该优惠券？`, '提示')
    if (row.enable == 1) {
      row.enable = 0
    } else {
      row.enable = 1
    }
    updateStatus(row).then((res: any) => {
      console.log(res)
      if (res.code == 200) {
        ElMessage.success('操作成功')
      } else {
        ElMessage.error('操作失败')
      }
    })

    console.log(row.enable)
    getList()
  } catch {
    ElMessage.error('操作失败')
  }
}

// 表单提交
const submitForm = debounce(
  async () => {
    console.log(form)

    if (!formRef.value) return
    await formRef.value.validate()
    if (form.id) {
      await updateCoupon(form)
    } else {
      await addCoupon(form)
    }
    ElMessage.success('操作成功')
    open.value = false
    getList()
  },
  1000,
  { leading: true, trailing: false },
)

// 发放优惠券提交
const submitGrant = () => {
  if (!grantFormRef.value) return
  grantFormRef.value.validate((valid) => {
    if (valid) {
      const couponId = grantForm.couponId
      const userIds = grantForm.userId.toString()
      grantCouponApi({ couponId: couponId, phones: userIds }).then((res: any) => {
        if (res.code == 200) {
          ElMessage.success('发放成功')
          openGrant.value = false
          Object.assign(grantForm, {
            couponId: '',
            userId: [],
          })
        }
      })
    }
  })
}

// 类型格式化
const typeFormat = (type: string) => {
  if (type == '0') {
    return '场馆'
  } else if (type == '1') {
    return '平安'
  } else if (type == '2') {
    return '平台'
  } else if (type == '3') {
    return '通用'
  }
  return ''
}

// 重置表单
const resetForm = () => {
  Object.assign(form, {
    id: null,
    couponName: null,
    type: null,
    enable: null,
    stadiumId: null,
    siteId: null,
    motionType: null,
    validity: null,
    stadiumName: null,
    siteName: null,
    startTime: null,
    endTime: null,
    discountType: null,
    totalLimit: 0.0,
    discountAmount: 0.0,
  })
  formRef.value?.clearValidate()
}

// 重置查询
const resetQuery = () => {
  Object.assign(queryParams, {
    pageNum: 1,
    pageSize: 10,
    couponName: null,
    type: null,
  })
  getList()
}

const searchStadium = async (query: string) => {
  if (query) {
    stadiumLoading.value = true
    try {
      const res: any = await quickSearchStadium({ keyword: query })
      stadiumOptions.value = res.data || []
    } finally {
      stadiumLoading.value = false
    }
  } else {
    stadiumOptions.value = []
  }
}

// 选中框值改变时触发
const handleStadiumChange = (selectedId: number) => {
  console.log(selectedId)
  form.stadiumId = selectedId
  if (selectedId == null || selectedId == undefined || selectedId == 0) {
    form.siteId = 0
    form.siteName = 0
    siteOptions.value = []
    return
  }
  //  根据场馆ID查找出所有场地信息
  handlSearchSiteByStadiumId()
}

const handleSiteChange = (selectedId: number) => {
  console.log(selectedId)
  form.siteId = selectedId
}

const handlSearchSiteByStadiumId = () => {
  //  根据场馆ID查找出所有场地信息
  getSitesByStadiumId({
    stadiumId: form.stadiumId!,
    type: form.motionType!,
  }).then((res: any) => {
    siteOptions.value = res.data
    console.log(res)
  })
}

// 选择运动类型
const changeMotionType = () => {
  form.siteId = 0
  form.siteName = 0
  if (form.stadiumId) {
    handlSearchSiteByStadiumId()
  }
}

const handleChange = (value: number) => {
  if (value == 2) {
    isQMShow.value = true
    isMJShow.value = false
  } else if (value == 3) {
    isMJShow.value = true
    isQMShow.value = false
  } else {
    isQMShow.value = false
    isMJShow.value = false
  }
  console.log('选中的值：' + value)
}

// 选择平台类型
const changePlatformType = (val: number) => {
  isDisabled.value = val == 2 || val == 3 ? true : false
  typeDisabled.value = val == 3 ? true : false
  if (val == 0) {
    // @ts-ignore
    rules.motionType = []
    // @ts-ignore
    rules.siteName = []
  } else {
    // @ts-ignore
    rules.motionType = [{ required: true, message: '请选择运动类型', trigger: 'change' }]
    // @ts-ignore
    rules.siteName = [{ required: true, message: '请选择场地', trigger: 'change' }]
  }
}

const handleClose = () => {
  resetForm()
  open.value = false
}

const grantClose = () => {
  openGrant.value = false
  Object.assign(grantForm, {
    couponId: '',
    userId: [],
  })
}

// 获取小程序用户列表
const getUserList = () => {
  getPage({ pageNum: 1, pageSize: 1000 }).then((res: any) => {
    userList.value = res.rows
  })
}

// 格式化运动类型
const motionTypeFormat = (item: any) => {
  for (let i = 0; i < dict.value.type.site_type.length; i++) {
    if (item.motionType == dict.value.type.site_type[i].value) {
      return dict.value.type.site_type[i].label
    } else {
      return '全部'
    }
  }
  return '全部'
}

// 查询
const handleQuery = () => {
  getList()
}

// 重置
const reset = () => {
  Object.assign(queryParams, {
    pageNum: 1,
    pageSize: 10,
    couponName: null,
    type: null,
    enable: null,
  })
  getList()
}

// 表格多选
const handleSelectionChange = (val: any[]) => {
  multipleSelection.value = val
}

// 页面挂载时执行
onMounted(() => {
  getList()
  getUserList()
})
</script>

<style lang="scss" scoped>
.search_box {
  padding-bottom: 0;
}
.table_box {
  padding-top: 15px;
  .handle_btn {
    margin-bottom: 11px;
  }
}
</style>
